﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using LinqToTwitter;

namespace MvcOAuth.Controllers
{
    public class DefaultController : Controller
    {
        readonly IOAuthCredentials _credentials = new SessionStateCredentials();

        private MvcAuthorizer _auth;
        private TwitterContext _twitterCtx;
        private string _userId;

        public ActionResult Index()
        {

            return View();
        }


        public ActionResult Login()
        {
            if (_credentials.ConsumerKey == null || _credentials.ConsumerSecret == null)
            {
                _credentials.ConsumerKey = ConfigurationManager.AppSettings["consumerKey"];
                _credentials.ConsumerSecret = ConfigurationManager.AppSettings["consumerSecret"];
            }

            _auth = new MvcAuthorizer
            {
                Credentials = _credentials
            };

            _auth.CompleteAuthorization(Request.Url);

            if (!_auth.IsAuthorized)
            {
                return _auth.BeginAuthorization();
            }

            Session["UserId"] = _auth.UserId;

            _twitterCtx = new TwitterContext(_auth);

           
            
            return RedirectToAction("Welcome");
        }

        public ActionResult Welcome()
        {
            _auth = new MvcAuthorizer
            {
                Credentials = _credentials
            };

           

            if (!_auth.IsAuthorized)
            {
                return _auth.BeginAuthorization();
            }

            _auth.UserId = Session["UserId"] as string;
            _twitterCtx = new TwitterContext(_auth);


            var twitterUser = (from u in _twitterCtx.User
                               where u.UserID == _auth.UserId && u.Type == UserType.Show
                              select new TwitterUser
                                         {
                                             Name = u.Name,
                                             //ScreenName = u.ScreenName,
                                             Description = u.Description,
                                             ProfileImageUrl = u.ProfileImageUrl
                                         }).FirstOrDefault();
           
            return View(twitterUser);
        }



       
    }
}
